<template>
  <div class="el-main">
    <el-main>
      <div class="block">
        <el-button type="primary" @click="addMeal">
          <i class="el-icon-circle-plus-outline"></i>
          添加菜品</el-button
        >
        <span class="demonstration"></span>
        <el-Cascader
          v-model="selectedOptions"
          :options="options"
          :props="{ expandTrigger: 'hover' }"
          @change="handleChange"
        ></el-Cascader>
      </div>
      <div class="main-content">
        <div class="tables-info">
          <div v-for="good in filteredGoods" :key="good.id" class="item-info">
            <img :src="good.mealPicture" alt="餐饮图片" class="table-image" />
            <div class="table-details">
              <p>菜 名：{{ good.mealName }}</p>
              <p>类 别：{{ good.mealType }}</p>
              <p>单 价：{{ good.price }}/份</p>
              <p>描 述：{{ good.description }}</p>

              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="gotoEdit(good)"
              >
                编 辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="delMeal(good.id)"
              >
                删 除</el-button
              >
            </div>
          </div>
        </div>

        <!-- 模态对话框 -->
        <el-dialog title="添加商品" :visible.sync="dialogVisible" width="30%">
          <el-form :model="temp" label-width="100px">
            <el-form-item label="图 片">
              <el-upload
                class="avatar"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="this.temp.mealPicture"
                  :src="this.temp.mealPicture"
                  class="mealpicture"
                  style="border-radius: 50%"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="菜 名">
              <el-input v-model="temp.mealName"></el-input>
            </el-form-item>
            <el-form-item label="类 别">
              <el-input v-model="temp.mealType"></el-input>
            </el-form-item>
            <el-form-item label="价 格">
              <el-input v-model="temp.price"></el-input>
            </el-form-item>
            <el-form-item label="描 述">
              <el-input v-model="temp.description"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelAdd">取消</el-button>
            <el-button v-if="editable" type="primary" @click="orderEdit"
              >修改</el-button
            >
            <el-button v-if="!editable" type="primary" @click="submitAdd"
              >添 加</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-main>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goods: [],
      dialogVisible: false,
      editable: false,
      options: [], // 存储从API获取的级联选择器选项
      selectedOptions: [],
      filteredGoods: [], // 根据级联选择器选择过滤的商品数据
      temp: {},
      uploadUrl: "http://localhost:8080/files/upload",
    };
  },
  mounted: function () {
    this.fetchOptions();
    this.getMealData();
  },
  methods: {
    addMeal() {
      this.dialogVisible = true;
      this.temp.mealNum = 1;
    },

    submitAdd: async function () {
      const response = await this.$http.post("goods/addGoods", this.temp);
      if (response.status === 200) {
        this.$message.success("添加成功");
        this.dialogVisible = false;
        this.getMealData();
      } else {
        this.$message.error("添加失败");
      }
    },
    gotoEdit(good) {
      this.dialogVisible = true;
      this.editable = true;
      this.temp = good;
    },
    orderEdit: async function (good) {
      const response = await this.$http.put("goods/updateGoods", this.temp);
      if (response.status === 200) {
        this.$message.success("修改成功");
        this.dialogVisible = false;
        this.temp = {};
        this.getMealData();
      } else {
        this.$message.error("修改失败");
      }
    },

    delMeal: async function (id) {
      this.$confirm("此操作将删除该菜品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("/goods/delGoods/" + id).then((response) => {
            if (response.status === 200) {
              this.goods.splice(index, 1);
              this.$message.success("删除成功");
            } else {
              this.$message.error(response.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    cancelAdd() {
      this.$message.info("已取消");
      this.dialogVisible = false;
      this.editable = false;
      this.temp = {};
    },

    async fetchOptions() {
      try {
        const response = await this.$http.get("/goods/getMealType");

        this.options = response.data.map((item) => ({
          value: item.mealType,
          label: item.mealType,
        }));
      } catch (error) {
        console.error("获取选项数据失败:", error);
      }
    },
    async getMealData() {
      try {
        const response = await this.$http.get("/goods/getAllGoods");
        this.goods = response.data;
        this.filteredGoods = this.goods;
      } catch (error) {
        console.error("获取商品数据失败:", error);
      }
    },

    handleChange(value) {
      this.filteredGoods = this.goods.filter((good) =>
        this.selectedOptions.includes(good.mealType)
      );
    },
    handleAvatarSuccess(response) {
      this.temp.mealPicture = response.data;
    },

    beforeAvatarUpload(file) {
      const isImage = file.type.match("image/*");
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error("上传头像图片只能是图像文件!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
  },
};
</script>


<style scoped>
.el-main {
  background-image: url("../assets/img/main.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed; /* 固定背景图像 */
  padding: 20px;
}

/*图标 */
.table-image {
  width: 100px;
  height: 80px;
  display: block;
  margin: 0 auto;
}

.main-content {
  text-align: center;
}

/*每个座位 */
.tables-info {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 项目向左对齐 */
  margin-top: 20px;
  font-size: 13px;
  gap: 10px;
}

/*与右边间隔 */
.table-item {
  margin-right: 160px;
}

.table-item:last-child {
  margin-right: 0; /* 重置最后一个项目的右边距 */
}

/*座位字段 */
.table-details {
  color: #99b9e1;
}

/*按钮设置*/
.table-details button {
  /* background-color: #f27c0d !important; */
  width: 99px; /* 设置按钮的宽度 */
  height: 40px; /* 设置按钮的高度 */
  padding: 10px 20px; /* 设置按钮的内边距，使按钮内部内容与边界有更多空间 */
  font-size: 14px; /* 设置按钮文本的大小 */
  line-height: 1; /* 确保文本高度与按钮高度一致 */
  border-radius: 5px; /* 设置按钮的圆角大小 */
  cursor: pointer; /* 鼠标悬停在按钮上时显示手形图标 */
}

.el-breadcrumb button {
  color: #faaa09; /* 文字的初始颜色 */
  border: none; /* 去掉边框 */
  background-color: transparent; /* 去掉背景色 */
  font-size: 20px; /* 文字的字体大小 */
  cursor: pointer; /* ��标���停在文字上时显示手形图标 */
}

.avatar {
  margin-bottom: 20px;
  width: 178px;
  height: 178px;

  background-color: #f9f9f9;
  border: 2px solid #110e0e;
  cursor: pointer;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center; /* 使图标在上传区域内居中 */
  margin-left: 22%;
}

.mealpicture {
  width: 178px;
  height: 178px;
  display: block;
}
</style>